package com.asen.commons.core.concurrent;

import com.asen.commons.utils.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程工厂
 *
 * @author Gary
 * @version 1.0
 * @date 2019-10-19
 */
public class GenericThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public GenericThreadFactory(String prefix) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        if (StringUtils.isEmpty(prefix)) {
            prefix = "default";
        }

        StringBuilder sb = new StringBuilder("scp-");
        sb.append(prefix);
        sb.append("-");
        sb.append(poolNumber.getAndIncrement());
        sb.append("-thread-");

        namePrefix = sb.toString();
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        t.setDaemon(false);
        t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}
